package cn.converter;

import com.opensymphony.xwork2.conversion.TypeConversionException;
import org.apache.struts2.util.StrutsTypeConverter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class DateConverter extends StrutsTypeConverter {

    private final DateFormat[] dfs = {
            new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy年MM月dd日"),
            new SimpleDateFormat("yyyy/MM/dd")
    };

    @Override
    public Object convertFromString(Map context, String[] values, Class toClass) {
        if(values == null || values.length == 0){
            return null;
        }
        String dateStr = values[0];
        for (int i =0;i<dfs.length;i++){
            try {
                return dfs[i].parse(dateStr);
            } catch (ParseException e) {
                continue;
            }
        }
        throw new TypeConversionException();
    }
    @Override
    public String convertToString(Map context, Object o) {
        Date date = (Date)o;
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }
}
